<?php

namespace App\Http\Controllers;

use App\Models\Station;
use Illuminate\Http\Request;
use App\Models\Station\Timing;
use Illuminate\Support\Facades\Auth;

/**
 * 报岗管理业务逻辑控制器
 *
 * Date: 30/04/2018
 * @author George
 * @package App\Http\Controllers
 */
class StationController extends Controller
{
	/**
	 * 根据项目获取报岗点信息
	 *
	 * Date: 30/04/2018
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function index(Request $request)
    {
    	$project_id = $request->get('project_id');
    	$paginate = $request->get('paginate', 15);
    	$name = $request->get('name');
    	$query = Station::query()->where('project_id', $project_id);

    	if ($name) {
    		$query->where('name', 'like', "%{$name}%");
		}

    	return success($query->paginate($paginate));
    }

	/**
	 * 创建报岗的岗位信息
	 *
	 * Date: 30/04/2018
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function store(Request $request)
    {
    	$attributes = $this->validate($request, [
    		'project_id' => 'required',
    		'longitude' => 'required',
    		'latitude' => 'required',
    		'image' => 'nullable',
    		'name' => 'required',
    		'assignment' => 'nullable'
		]);

    	$attributes['company_id'] = Auth::user()->company_id;

    	$station = Station::create($attributes);
    	return stored($station);
    }

	/**
	 * 获取报岗点详情
	 *
	 * Date: 30/04/2018
	 * @author George
	 * @param Station $station
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function show(Station $station)
    {
    	$station->schedules = $station->schedules()->get();
    	return success($station);
    }

	/**
	 * 更新报岗点信息
	 *
	 * Date: 30/04/2018
	 * @author George
	 * @param Request $request
	 * @param Station $station
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function update(Request $request, Station $station)
    {
		$attributes = $this->validate($request, [
			'longitude' => 'required',
			'latitude' => 'required',
			'image' => 'nullable',
			'name' => 'required',
			'assignment' => 'nullable'
		]);

		$station->update($attributes);
		return updated($station);
    }

	/**
	 * 删除报岗点
	 *
	 * Date: 30/04/2018
	 * @author George
	 * @param Station $station
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \Exception
	 */
    public function destroy(Station $station)
    {
    	$station->delete();
    	return deleted();
    }

	/**
	 * 创建报岗计划
	 *
	 * Date: 01/05/2018
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function schedule(Request $request)
	{
		$attributes = $this->validate($request, [
			'project_id' => 'required|integer',
			'station_id' => 'required|integer',
			'genre_id' => 'required|integer',
			'time' => 'required',
			'delayed' => 'required|integer'
		]);
		$record = Timing::create($attributes);
		return stored($record);
    }
}
